<?php

	function is_not($id){
		$result["result"] = false;
		$result["message"] = $id;
		return $result;
	}
	function get_rong_appSec(){
		return C('RONG_DEV_APP_SECRET');
	}
	function get_tong_AppKey(){
		return C('RONG_DEV_APP_KEY');
	}
	function get_user()
	{
		return session('uid.id') ? session('uid.id') : 1;
	}
	function is_login(){

		$userinfo = session('uid.id');
		if (!$userinfo) 
		{	
			$url = 'http://'.C('INT_COM').'/index.php/Home/Index/user_login';

			if ($_SERVER['SERVER_NAME'] != C('INT_COM')) 
			{
				$url = 'http://'.$_SERVER['SERVER_NAME'].'/next/index.php/Home/Index/user_login';
			}
			header("Location: $url");exit();
            // $this->redirect('Index/user_login');
		}

		$user = M('user')->where("id=".$userinfo)->find();
		
		$urls = 'http://'.C('INT_COM').'/index.php/Home/Index/user_forget?type=complete';

		if ($_SERVER['SERVER_NAME'] != C('INT_COM')) 
		{
			$urls = 'http://'.$_SERVER['SERVER_NAME'].'/next/index.php/Home/Index/user_forget?type=complete';
		}
		if (!$user['phone']) {
			// dump(111);exit();
			header("Location: $urls");exit();
		}

		if ($user['is_verify']==0) {
			$url1 = 'http://'.C('INT_COM').'/index.php/Home/Index/user_identify';
			header("Location: $url1");exit();
			// $this->redirect("Index/user_identify");
		}

		if (!$user['photo_id'] || stristr($user['photo_id'],'wx.qlogo')) 
		{	
			$url2 = 'http://'.C('INT_COM').'/index.php/Home/Index/user_header';
			header("Location: $url2");exit();
			$this->redirect("Index/user_header");
		}
	}
	function getdistance($lng1,$lat1,$lng2,$lat2)//根据经纬度计算距离
	{
	    //将角度转为弧度
	    $radLat1=deg2rad($lat1);
	    $radLat2=deg2rad($lat2);
	    $radLng1=deg2rad($lng1);
	    $radLng2=deg2rad($lng2);
	    $a=$radLat1-$radLat2;//两纬度之差,纬度<90
	    $b=$radLng1-$radLng2;//两经度之差纬度<180
	    $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
	    $s=round($s,1);
	    return $s;
	}

    //打印日志
	function dlog($message, $format = false, $newline = false)
	{	
		if (empty($_SERVER["HTTP_HOST"]))
		{	
			return;
		}

		$now = date("Y-m-d H:i:s");

		// if (is_array($message))

			$message = json_encode($message, JSON_UNESCAPED_UNICODE | ($format ? JSON_PRETTY_PRINT : true)) . ($newline ? "\n" : "");
			// dump($message);exit();
			$msg = sprintf("%s %s", $now, $message . "\n");
			$dir = ROOT_PATH ."/Runtime/Logs/dlog";
			$cache_file_path = $dir . "/debug." . date("Ymd") . ".log";
			if (!file_exists($dir))
			{
				if (@mkdir(rtrim($dir, "/"), 755))
				{
					@chmod($dir, 755);
				}
			}
		file_put_contents($cache_file_path, $msg, FILE_APPEND);
	}
//报名成功之后抢到的红包放到自己的钱包中。
function add_redmoney_log($money,$user_id,$start_time,$type=1,$activity_id = 0){
	//间隔时间
	if ($type=1) {$interval = 24*3600;}else{$interval = 3*3600;}
	//讲钱放到红包中，状态值设置为0
	//红包数据
	$data = array(
		'activity_id'=> $activity_id,
		'user_id' => $user_id,
		'money'	  => $money,
		'type'	  => 1,
		'status'  => 1,
		'add_time'=> time(),
		'get_time'=> $start_time + $interval,
	);
	$res = M('red_money')->add($data);
	return $res ? $res : false;
}

function curlGet($url,$data){
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt ($ch, CURLOPT_HEADER, false);
    curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false);
	
    $temp = curl_exec($ch);
    curl_close($ch);
    return $temp;
}

//通过url，postdata，请求头获取信息
function urlGetJson($url,$postData,$httpHeader){
	$ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    $yyx_result = curl_exec($ch);
    $yyx_data=json_decode($yyx_result,true);
    curl_close($ch);
    return $yyx_data;
}
//获取用户token
function get_rong_token($user_id){
	$result['id']= $user_id;
	$appSec= get_rong_appSec();
    $nonce = mt_rand();
    $timeStamp = time();
    $signature = sha1($appSec.$nonce.$timeStamp);    //$appSec是平台分配
    $url = 'http://api.cn.ronghub.com/user/getToken.json';
    // $url = 'https://api.cn.rong.io/user/getToken.json';
    $postData = 'userId='.$result['id'];
    $httpHeader = array(
    'App-Key:'.get_tong_AppKey(),   //平台分配
    'Nonce:'.$nonce,        //随机数
    'Timestamp:'.$timeStamp,    //时间戳
    'Signature:'.$signature,         //签名
    'Content-Type: application/x-www-form-urlencoded',
    );
    $yyx_data = urlGetJson($url,$postData,$httpHeader);
    $result['rong_id']=$yyx_data['token'];
    return $yyx_data['token'];
}

// 单挑消息
function system_to_one($user_id,$content,$extra){
	$wxopanid = M('user')->where(array('id'=>$user_id))->getField('openid');
	$status = get_rong_status($user_id);
	if ($status ==0) 
	{	
		if (C('NEWS_CONFIG') == '1') 
		{
			$num = M('message')->where(array('shou_id'=>$user_id,'status'=>0))->count();
			$content = "您有".$num."条消息未读";
		}else{
			$content = $content;
		}
		$news = A('Index')->wx_message($wxopanid,urldecode($content));
	}
    $appSec = get_rong_appSec();
    $nonce = mt_rand();
    $timeStamp = time();
    $signature = sha1($appSec.$nonce.$timeStamp);    //$appSec是平台分配
    $url = 'https://api.cn.ronghub.com/message/system/publish.json';
    $content='{"content":"'.$content.'","extra":"'.$extra.'"}';
    $content=urlencode($content);
    $postData ='fromUserId=System&toUserId='.$uesr_id.'&objectName=RC%3ATxtMsg&content='.$content;
    $httpHeader = array(
    'App-Key:'.get_tong_AppKey(),   //平台分配
    'Nonce:'.$nonce,        //随机数
    'Timestamp:'.$timeStamp,    //时间戳
    'Signature:'.$signature,         //签名
    'Content-Type: application/x-www-form-urlencoded',
    );
    $datalist=urlGetJson($url,$postData,$httpHeader);
    
    return $datalist['code'];
}

// 检测有没有在线
function get_rong_status($user_id){
	$result['id']= $user_id;
	$appSec= get_rong_appSec();
    $nonce = mt_rand();
    $timeStamp = time();
    $signature = sha1($appSec.$nonce.$timeStamp);    //$appSec是平台分配
    $url = 'http://api.cn.ronghub.com/user/checkOnline.json';
    // $url = 'https://api.cn.rong.io/user/getToken.json';
    $postData = 'userId='.$result['id'];
    $httpHeader = array(
    'App-Key:'.get_tong_AppKey(),   //平台分配
    'Nonce:'.$nonce,        //随机数
    'Timestamp:'.$timeStamp,    //时间戳
    'Signature:'.$signature,         //签名
    'Content-Type: application/x-www-form-urlencoded',
    );
    $yyx_data = urlGetJson($url,$postData,$httpHeader);
    $result['status']=$yyx_data['status'];
    return $yyx_data['status'];
}

	/**
     * 一天的接口调用次数限制
     *
     * @access  private
     * @param   user_id     用户id
     * @param   int     
     * @return  false
     */
function auth_num($user_id){
	if (time()> (S('ids'.$user_id)['gtime']))
	{
		$data = array(
			'num'=>0,
			'gtime'=>0,
			);
		S('ids'.$user_id,$data,24*60*60);
	}

	if (S('ids'.$user_id)['num']<5)
	{
		$data = array(
			'num'=>S('ids'.$user_id)['num']+1,
			'gtime'=>strtotime(date('Y-m-d',strtotime('+1 day'))),
			);

		S('ids'.$user_id,$data,24*60*60);

	}else
	{
	    return false;
	}
}



    /**
     * code 生成
     *
     * @access  private
     * @param   int     $urls $id $img $names  上级分类ID
     * @param   int     $      级别
     * @return  void
     */
	function addCode($urls,$id,$img){
		//二维码图片保存路径
		$pathname ='2017code';// date("Ymd",time());
		$pathname = "./Public/Uploads/Company/" . $pathname;
		$pathnames = "/Public/Uploads/Company/2017code";
		if(!is_dir($pathname)) { //若目录不存在则创建之
		mkdir($pathname);
		}
		vendor("phpqrcode.phpqrcode");

		//二维码URL参数
		$text = $urls;//"http://www.baidu.com"; 
		//二维码图片保存路径(若不生成文件则设置为false)
		$filename = $pathname . "/qrcode_".$id. time() . ".png";
		$save = $pathnames . "/qrcode_".$id. time() . ".png";
		//二维码容错率，默认L
		$level = "L";
		//二维码图片每个黑点的像素，默认4
		$size = '4';
		//二维码边框的间距，默认2
		$padding = 2;
		//保存二维码图片并显示出来，$filename必须传递文件路径
		$saveandprint = true;

		//生成二维码图片
		\QRcode::png($text,$filename,$level,$size,$padding,$saveandprint);

		//二维码logo
		if ($img) 
		{
			$logo = $img;
		}

		$QR = imagecreatefromstring(file_get_contents($filename));
		$logo = imagecreatefromstring(file_get_contents($logo));
		$QR_width = imagesx($QR);
		$QR_height = imagesy($QR);
		$logo_width = imagesx($logo);
		$logo_height = imagesy($logo);
		$logo_qr_width = $QR_width / 5;
		$scale = $logo_width / $logo_qr_width;
		$logo_qr_height = $logo_height / $scale;
		$from_width = ($QR_width - $logo_qr_width) / 2;
		imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
		imagepng($QR,$filename);

		// $image = new \Think\Image(); // 在图片右下角添加水印文字 ThinkPHP 并保存为new.jpg

		// $image->open($filename)->water($logo,\Think\Image::IMAGE_WATER_CENTER,50)->save($filename); 
		// $name = '厦门净邦生物科技有限公司  '.$names;
		// $image->open($filename)->crop(405, 405)->save($filename);   //将图片裁剪为400x400并保存为corp.jpg
		// $image->open($filename)->text('SINGBO 净邦','./simsun.ttc',25,'#1AA025',\Think\Image::IMAGE_WATER_NORTH)->save($filename);
		// $image->open($filename)->text($names,'./simsun.ttc',20,'#000000',\Think\Image::IMAGE_WATER_SOUTH)->save($filename);

		// echo '<img src="http://zm.com'.__ROOT__.$filename.'">';exit();
		$url = $save;
		return $url;
	}


function getLoginTime($login_time){
	$diff = time() - $login_time;
	if ($diff <= 60) {
		return '1m前';
	}elseif($diff <= 3600){
		$diff_to_minu = intval($diff/60);
		return $diff_to_minu.'m前';
	}elseif($diff <= 24*3600){
		$diff_to_hour = intval($diff / 3600);
		return $diff_to_hour.'h前';
	}else{
		return date('Y-m-d',$login_time);
	}
}

    function getBmStrStatus($bm_log){
        /*if($bm_log['is_arrive'] == 1){
            if($bm_log['is_gift'] == 1){
                $bm_user['bm_str_status'] = "已领见面礼";
            }else{$bm_user['bm_str_status'] = "未领见面礼";}
        }elseif($bm_log['is_invited'] == 2){
            $bm_user['bm_str_status'] = "已被邀约";
        }elseif($bm_log['is_invited'] == 1){
            $bm_user['bm_str_status'] = "等待邀约";
        }*/
        if($bm_log['is_arrive'] == 1){
            if($bm_log['is_gift'] == 1){
                return "已领见面礼";
            }else{return "未领见面礼";}
        }elseif($bm_log['is_invited'] == 2){
            return "已被邀约";
        }elseif($bm_log['is_invited'] == 1){
            return "等待邀约";
        }
    }




/** 
    * 取汉字的第一个字的首字母 
    * @param type $str 
    * @return string|null 
    */  
function _getFirstCharter($str){  
	if(empty($str)){return '';}  
	$fchar=ord($str{0});  
	if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});  
	$s1=iconv('UTF-8','gb2312',$str);  
	$s2=iconv('gb2312','UTF-8',$s1);  
	$s=$s2==$str?$s1:$str;  
	$asc=ord($s{0})*256+ord($s{1})-65536;  
	if($asc>=-20319&&$asc<=-20284) return 'A';  
	if($asc>=-20283&&$asc<=-19776) return 'B';  
	if($asc>=-19775&&$asc<=-19219) return 'C';  
	if($asc>=-19218&&$asc<=-18711) return 'D';  
	if($asc>=-18710&&$asc<=-18527) return 'E';  
	if($asc>=-18526&&$asc<=-18240) return 'F';  
	if($asc>=-18239&&$asc<=-17923) return 'G';  
	if($asc>=-17922&&$asc<=-17418) return 'H';  
	if($asc>=-17417&&$asc<=-16475) return 'J';  
	if($asc>=-16474&&$asc<=-16213) return 'K';  
	if($asc>=-16212&&$asc<=-15641) return 'L';  
	if($asc>=-15640&&$asc<=-15166) return 'M';  
	if($asc>=-15165&&$asc<=-14923) return 'N';  
	if($asc>=-14922&&$asc<=-14915) return 'O';  
	if($asc>=-14914&&$asc<=-14631) return 'P';  
	if($asc>=-14630&&$asc<=-14150) return 'Q';  
	if($asc>=-14149&&$asc<=-14091) return 'R';  
	if($asc>=-14090&&$asc<=-13319) return 'S';  
	if($asc>=-13318&&$asc<=-12839) return 'T';  
	if($asc>=-12838&&$asc<=-12557) return 'W';  
	if($asc>=-12556&&$asc<=-11848) return 'X';  
	if($asc>=-11847&&$asc<=-11056) return 'Y';  
	if($asc>=-11055&&$asc<=-10247) return 'Z';  
	return null;  
}  


	/** 
    * 判断两人是否都已经到达，如果都已到达，接着判断是否是好友关系，如果是好友关系，则跳过
    * 如果不是好友则添加好友
    * @param model $activity 
    * @return bool $is_self
    */  
    function judgeFriend($activity,$user_id){
		//如果已经到达，判断是否是好友
		$is_friend = M('contact')->where(array('user1'=>$activity['user_id'],'user2'=>$user_id))->find();
		if(!$is_friend){
			//如果还不是好友关系，则添加好友关系
			$data[0] = array('user1'=>$activity['user_id'],'user2'=>$user_id,'add_time'=>time());
			$data[1] = array('user1'=>$user_id,'user2'=>$activity['user_id'],'add_time'=>time());
			M('contact')->add($data[0]);
			M('contact')->add($data[1]);
		}
    }

    function cancelFriend($user_id,$activi){
    	$friend = M('contact')->where("user1=".$user_id." AND user2=".$activi['user_id'])->find();
    	if(!$friend){
			M('follow')->where("(user_id=".$user_id." AND fo_user_id=".$activi['user_id'].") OR (user_id=".$activi['user_id']." AND fo_user_id=".$user_id.")")->save(array('is_friend' => 0)); 		
    	}
    }

    function getThemeImg($theme){
		$num = array();
		if($theme == 1){
			$type=2;
			$title = "美食小酌";
		}elseif ($theme == 2) {
			$type=1;
			$title = "K歌畅饮";
		}else{
			$type=0;
			$title = "酒吧狂欢";
		}
		$photos = M('slide')->where('type='.$type)->select();
		foreach ($photos as $key => $value) {
			if($value['status'] == 1){
				$num['id'] = $value['id'];
				$num['key'] = $key;
				break;
			}
		}
		if(empty($num)){
			$image = $photos[0]['image'];
			M('slide')->where('id='.$photos[1]['id'])->save(array('status'=>1));
		}else{
			$image = $photos[$num['key']]['image'];
			M('slide')->where('id='.$photos[$num['key']]['id'])->save(array('status'=>0));
			if($num['key'] >= (count($photos)-1)){
				M('slide')->where('id='.$photos[0]['id'])->save(array('status'=>1));
			}else{
				M('slide')->where('id='.$photos[$num['key'] + 1]['id'])->save(array('status'=>1));
			}
		}
		return array(
			'image'=>$image,
			'title'=>$title
		);
    }
